package com.lwm.jdbc.jdbc;

import com.lwm.jdbc.pojo.AccountDO;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * JdbcTemplate demo
 *
 * @author liweimin
 * @date 2021/6/11 12:51
 * @since
 */
public class JdbcTemplateDemo {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate template = context.getBean("jdbcTemplate", JdbcTemplate.class);
//        template.execute("insert into account(name,money) values ('eee',1000)");


        /**
         * JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);  // reusable object
         *    RowMapper rowMapper = new UserRowMapper();  // reusable object
         *
         *    List allUsers = (List) jdbcTemplate.query(
         *        "select * from user",
         *        new RowMapperResultSetExtractor(rowMapper, 10));
         *
         *    User user = (User) jdbcTemplate.queryForObject(
         *        "select * from user where id=?", new Object[] {id},
         *        new RowMapperResultSetExtractor(rowMapper, 1));
         */
        RowMapper<AccountDO> mapper = new RowMapper<AccountDO>() {
            @Override
            public AccountDO mapRow(ResultSet rs, int rowNum) throws SQLException {
                String name = rs.getString("name");
                int id = rs.getInt("id");
                float money = rs.getFloat("money");
                return new AccountDO(id, name, money);
            }
        };
        List<AccountDO> list = (List<AccountDO>) template.query("select * from account", new RowMapperResultSetExtractor(mapper, 100));
        System.out.println(list);

        List<AccountDO> list1 = template.query("select * from account where id = ?", mapper, 1);

        System.out.println(list1);


        List<AccountDO> query = template.query("", mapper);

    }
}
